# coding: utf-8

# 全局方法
def global_method()
	puts "global_method"
end

global_method

class TestClass
	def instance_method()
		puts "instance_method"
	end

	def TestClass.class_method()
		puts "class_method"
	end
end

# 类型方法本质上是单利方法。
TestClass.class_method

test = TestClass.new
test.instance_method

def test.singleton_method()
	puts "singleton_method"
end

test.singleton_method

# 方法别名
def hello # A nice simple method
	puts "Hello World" # Suppose we want to augment it...
end

alias original_hello hello # Give the method a backup name

def hello # Now we define a new method with the old name
	puts "Your attention please" # That does some stuff
	original_hello # Then calls the original method
	puts "This has been a test" # Then does some more stuff
end

hello

# 方法参数
def test_method(x, y, z, map, *args)
	puts x, y, z, map, args
end

test_method 1, 2, 3, { name: "段光伟" }, 4, 5, 6

a, b = [1, 2, 3], [4, 5] # Start with some data.
summation = Proc.new {|total, x| total + x } # A Proc object for summations.
puts a.inject(0, &summation) # => 6
puts b.inject(0, &summation) # => 15

puts ["hello", "hi"].map &:upcase

# Proc
x = 1
p = Proc.new {|y| x + y}

puts p.call 1

# lambda
x = 1
la = lambda {|y| x + y}

puts la.call 1

la = ->(y){ x + y }

puts la.call 1

# block就像C#的大括号
def test_method()
  	puts "entering method"
  	1.times { puts "entering block"; return }  # Makes test method return
  	puts "exiting method"  # This line is never executed
end
test_method

# Proc是block的对象版本
def test_method
  puts "entering method"
  p = Proc.new { puts "entering proc"; return } 
  p.call                 # Invoking the proc makes method return
  puts "exiting method"  # This line is never executed
end
test_method

# lambda就像匿名方法
def test_method
  	puts "entering method"
  	p = ->() { puts "entering lambda"; return } 
  	p.call                 # Invoking the lambda does not make the method return
  	puts "exiting method"  # This line *is* executed now
end
test_method

def test_method
  	puts "entering test method"
  	lambda = lambda { puts "entering lambda"; break; puts "exiting lambda" }
  	lambda.call  
  	puts "exiting test method"
end
test_method




